<template>
  <div class="app-container">
    <div>
      <el-row>
        <el-col :span="4">
          <strong style="font-size: 20px;">
            提成设置
          </strong>
        </el-col>
        <el-col :span="20" align="right">
          <el-row>
            <el-col :span="6"><div class="grid-content bg-purple">
              <span style="margin-right: .5em">
                <el-select
                  v-model="category"
                  style="width: 250px;"
                  placeholder="产品分类"
                  filterable
                  clearable
                  @change="getSpecifications()"
                >
                  <el-option
                    v-for="item in categories"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </span>
            </div></el-col>
            <el-col :span="6"><div class="grid-content bg-purple">
              <span style="margin-right: .5em">
                <el-input v-model="keyword" placeholder="请输入商品名称" />
              </span>
            </div></el-col>
            <el-col :span="6"><div class="grid-content bg-purple">
              <span style="margin-right: .5em">
                <el-button size="medium" icon="el-el-icon-search" plain @click="getSpecifications()">
                  查找
                </el-button>
              </span>
              <span style="margin-right: .5em">
                <el-button size="medium" type="primary" icon="el-icon-plus" plain @click="totalExport()">
                  导出
                </el-button>
              </span>
            </div></el-col>
            <el-col :span="4"><div class="grid-content bg-purple-light" /></el-col>
          </el-row>

        </el-col>
      </el-row>
      <div style="width: 100%;padding-top: 10px;">
        <el-table
          :key="refreshTable"
          v-loading="loading"
          :data="list"
          element-loading-text="加载中..."
          height="70vh"
          fit
          lazy
          stripe
          highlight-current-row
          border
          style="width: 100%"
          :header-cell-style="{'text-align':'center'}"
        >
          <el-table-column fixed prop="productName" label="商品名称" />
          <el-table-column fixed prop="name" label="规格" width="100" />
          <el-table-column fixed prop="price" label="售价(元)" :width="width" />
          <el-table-column label="业务员">
            <el-table-column label="提成（元）" :width="width">
              <template slot-scope="scope">
                <el-input v-model="scope.row[1].value" type="number" />
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="门店(核销人)">
            <el-table-column label="佣金（元）" :width="width">
              <template slot-scope="scope">
                <el-input v-model="scope.row[4].value" type="number" />
              </template>
            </el-table-column>
          </el-table-column>
          <!-- <el-table-column label="支付手续费">
            <el-table-column label="扣除（元）" :width="width">
              <template slot-scope="scope">
                <el-input v-model="scope.row[2].value" type="number" />
              </template>
            </el-table-column>
          </el-table-column> -->
          <el-table-column label="平台">
            <el-table-column label="服务费（元）" :width="width">
              <template slot-scope="scope">
                <el-input v-model="scope.row[3].value" type="number" />
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
      </div>
      <div style="padding-top: 10px;">
        <el-button type="primary" icon="el-icon-edit-outline" @click="submit()">保存</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import exportExcelCsv from '@/utils/exportExcelCsv'
export default {
  data() {
    return {
      keyword: '',
      loading: false,
      list: [],
      refreshTable: 0,
      types: {
        1: '下单人佣金',
        2: '支付手续费',
        3: '平台佣金',
        4: '门店(核销人)佣金'
      },
      width: 130,
      storeCatrgories: [],
      storeCategory: '',
      categories: [],
      category: '',
      profitRules: [],
      profitRule: ''
    }
  },
  created() {
    this.getCategories()
  },
  methods: {
    // 选择提成方案时候，替换成提成方案的设置
    changeProfitRule() {
      console.log(this.profitRule)
      this.getSpecifications()
    },
    totalExport() {
      // table数据
      const list = JSON.parse(JSON.stringify(this.list))
      if (list.length === 0) {
        this.$message.error('暂无导出数据')
        return
      }
      const label = {
        'productName': '产品',
        'categoryName': '分类',
        'price': '售价',
        'salse': '业务员',
        'store': '门店(核销人)',
        'fee': '支付费率',
        'platform': '平台佣金'
      }
      const data = []
      list.map(v => {
        data.push({
          productName: v.productName,
          categoryName: v.categoryName,
          price: v.price,
          salse: v['1'].value,
          store: v['4'].value,
          fee: v['2'].value,
          platform: v['3'].value
        })
      })

      exportExcelCsv(label, data, `export-admin-commision.csv`)
    },
    // 根据门店出来对应的类型
    getCategories() {
      this.categories = []
      this.category = ''
      this.list = []
      this.axios.get(`/manage/categories`, {
        params: {
          '@filter': `entity.getType().getSlug() == 'product'`
        }
      }).then((res) => {
        this.categories = res.data
        this.category = res.data[0].id
        this.getSpecifications()
      })
    },
    getSpecifications() {
      this.list = []
      this.loading = true
      let filter = `entity.getProduct().getIsOnSale() == true`
      if (this.category !== '') {
        filter += ` && entity.getProduct().getCategory().getId() == ${this.category}`
      }
      if (this.keyword.trim() !== '') {
        filter += ` && entity.getProduct().getName() matches '${this.keyword}'`
      }
      this.axios.get(`/manage/specifications`, {
        params: {
          '@filter': filter,
          '@display': `{
            'id' : 'entity.getId()',
            'name' : 'entity.getProduct().getName()',
            'specName': 'entity.getName()',
            'category' : 'entity.getProduct().getCategory().getName()',
            'profitSettings': 'entity.getProfitSettings()',
            'price': 'entity.getPrice()'
          }`,
          // '@expands': `['entity.product','entity.profitSettings']`,
          limit: 10000000
        }
      }).then(res => {
        console.log('specc', res.data)
        if (res.data.length > 0) {
          const list = []
          for (var item of res.data) {
            const listItem = {}
            listItem['productName'] = item.name
            listItem['name'] = item.specName
            listItem['categoryName'] = item.category
            listItem['price'] = item.price
            // 获取specification所有profitSettings
            const profitSettings = item.profitSettings
            // 先初始化方案，全部加，加完下面查，有的替换，无的，就默认0
            for (let i = 0; i < 13; i++) {
              listItem[i] = {
                id: null,
                type: i,
                specification: item.id,
                value: 0
              }
              if (parseInt(this.profitRule) > 0) {
                listItem[i]['rule'] = this.profitRule
                const setting = profitSettings.find(v => v.type === i && v.rule && v.rule.id === this.profitRule)
                if (setting) {
                  listItem[i]['id'] = setting.id
                  listItem[i]['value'] = setting.value
                }
              } else {
                const setting = profitSettings.find(v => v.type === i && !v.rule)
                if (setting) {
                  listItem[i]['id'] = setting.id
                  listItem[i]['value'] = setting.value
                }
              }
            }
            list.push(listItem)
          }
          this.list = list
          console.log('list', this.list)
        }
      }).finally(() => { this.loading = false })
    },
    submit() {
      console.log('tijiao', this.list)
      if (this.loading) {
        return
      }
      if (this.list.length === 0) {
        this.$message.error('列表暂无数据!')
        return
      }
      const loading = this.$loading({
        lock: true,
        text: '数据交互中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const promise = []
      for (var item of this.list) {
        const listData = []
        for (let i = 0; i < 13; i++) {
          if (item[i].value > 0 || item[i].id != null) {
            listData.push(item[i])
          }
        }
        console.log('updateList', listData)
        if (listData.length > 0) {
          promise.push(
            this.axios.post(`/manage/profit-settings/batch-update`, listData,
              { params: { '@mode': 'mixed', '@basis': 'id' }})
          )
        }
      }
      Promise.all(promise).then(res => {
        loading.close()
        this.$message.success('数据上送成功')
        this.getSpecifications()
      })
    }
  }
}
</script>
